<template>
  <card id="card">
    <Tabs :value="selectTabPane" @on-click="clickTabs">
        <TabPane name="1" label="基本信息" icon="ios-folder-outline">
            <Form ref="formItem" :model="formItem" :rules="ruleForm" :label-width="120">
                <Row type="flex">
                    <Col span="6">
                        <FormItem label="疗程名称：" prop="name">
                            <Input v-model="formItem.name" size="large" placeholder="请填写内容...">
                                <Icon type="information-circled" slot="prepend"></Icon>
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="6">
                        <FormItem label="疗程价格：" prop="price">
                            <Input v-model="formItem.price" size="large" placeholder="请填写内容...">
                                <Icon type="social-yen-outline" slot="prepend"></Icon>
                            </Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex">
                    <Col span="24">
                        <FormItem>
                            <Button @click="save" size="large" type="primary">保存</Button>
                            <Button @click="close" size="large" type="ghost" style="margin-left: 8px">关闭</Button>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </TabPane>
        <TabPane name="2" label="项目明细" icon="ios-folder-outline" :disabled="disabled">
            <iview-table
                ref="iviewTable"
                :baseURL="queryModel.baseURL"
                :menuId="dataModel.menuId"
                :columns="dataModel.columns"
                :order="dataModel.order"
                :pageNumber="pageModel.pageNumber"
                :pageSize="pageModel.pageSize"
                :defaultFilters="queryModel.defaultFilters"
                v-on="{changeTotalSize:changeTotalSize,events:events,changeSelect:changeSelect}">
            </iview-table>
            <br>
            <iview-page 
                :totalSize="pageModel.totalSize"
                :pageNumber="pageModel.pageNumber" 
                :pageSize="pageModel.pageSize"
                :pageSizeOpts="pageModel.pageSizeOpts"
                v-on="{changePageNumber:changePageNumber,changePageSize:changePageSize}">
            </iview-page>
        </TabPane>
        <TabPane name="3" label="项目明细-基本信息" icon="ios-folder-outline" :disabled="disabled">
            <Form ref="formDetailItem" :model="formDetailItem" :rules="ruleDetailForm" :label-width="120">
                <Row type="flex">
                    <Col span="6">
                        <FormItem label="治疗项目：" prop="itemId">
                            <Select transfer=true filterable clearable v-model="formDetailItem.itemId" size="large" style="width:100%" :label-in-value=true @on-change="changeProject">
                                <Option v-for="item in projects" :value="item.id" :label="item.name" :key="item.id">
                                    <span>{{ item.name }}</span>
                                    <span style="float:right;color:#ccc">({{ item.projectTypeName }} / {{ item.price }} / 次)</span>
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="6">
                        <FormItem label="项目单价：" prop="price">
                            <Input readonly v-model="formDetailItem.price" size="large" placeholder="请输入价格...">
                                <Icon type="social-yen-outline" slot="prepend"></Icon>
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="6">
                        <FormItem label="治疗次数：" prop="quantity">
                            <Input v-model="formDetailItem.quantity" size="large" placeholder="请输入次数...">
                                <Icon type="social-yen-outline" slot="prepend"></Icon>
                            </Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex">
                    <Col span="24">
                        <FormItem>
                            <Button @click="saveDetails" size="large" type="primary">保存</Button>
                            <Button @click="close" size="large" type="ghost" style="margin-left: 8px">关闭</Button>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </TabPane>
    </Tabs>
  </card>
</template>

<script>
import iviewTable from '@/view/common/table/Table.vue';
import iviewPage from '@/view/common/page/Page.vue';
export default {
    components: {
        iviewTable,
        iviewPage
    },
    data () {
        return {
            courseId: '',
            baseURL: '/user/course',
            detailURL: '/user/course/details',
            projectURL: '/user/project',
            selectTabPane: '1',
            disabled: true,
            projects: [],
            selectProject: {},
            formItem: {
                id: '',
                name: '',
                originalPrice: '',
                price: ''
            },
            formDetailItem: {
                id: '',
                courseId: '',
                itemId: '',
                itemName: '',
                price: '',
                quantity: ''
            },
            ruleForm: {
                name: [
                    { required: true, message: '请填写疗程名称', pattern: /.+/, trigger: 'change' }
                ],
                price: [
                    { required: true, message: '请输入疗程价格', pattern: /.+/, trigger: 'change' }
                ]
            },
            ruleDetailForm: {
                itemId: [
                    { required: true, message: '请选择治疗项目', pattern: /.+/, trigger: 'change' }
                ],
                quantity: [
                    { required: true, message: '请输入治疗次数', pattern: /.+/, trigger: 'change' }
                ]
            },
            queryModel: {
                // 网关代理路径(必须)+资源路径(可选)
                baseURL: '/user/course/details',
                defaultFilters: [
                    {'field': 'course_id', 'value1': -1, 'operate': '=='}
                ]
            },
            dataModel: {
                menuId: 2500,
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },{
                        title: '项目名称',
                        key: 'itemName'
                    },{
                        title: '项目单价',
                        key: 'price'
                    },{
                        title: '治疗次数',
                        key: 'quantity'
                    }
                ],
                order: 'id desc'
            },
            pageModel: {
                totalSize: 0,
                pageNumber: 1,
                pageSize: 10,
                pageSizeOpts: [10, 50, 100, 500]
            }
        }
    },
    methods: {
        init () {
            document.getElementById("card").style.height = (document.documentElement.clientHeight /100 * 86 ) + 'px'
            this.reset()
            this.disabled = true
            this.selectTabPane = '1'
            this.formDetailItem.id = ''
            this.$bus.init(this.formDetailItem)
            // 加载治疗项目
            this.loadProject()
            // 表单初始化
            this.$bus.fillData(this.formItem, this.$route.query.row)
            if (this.$route.query.row) {
                this.formDetailItem.courseId = this.$route.query.row.id
                this.disabled = false
            }
        },
        loadProject () {
            let url = this.projectURL + '/findAll'
            this.$ajax.get(url).then((response) => {
                let {code, data, msg} = response.data
                if (code === 0) {
                    this.projects = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        events (item) {
            let path = item.path
            if (path === 'edit') {
                this.edit()
            } else if (path === 'delete') {
                this.delete()
            }
        },
        edit () {
            if (this.selectRows.length === 1) {
                this.$bus.fillData(this.formDetailItem, this.selectRows[0])
                this.formDetailItem.itemId = parseInt(this.selectRows[0].itemId)
                this.selectTabPane = '3'
            } else {
                this.$bus.alert('warning', '请选择一条记录')
            }
        },
        delete () {
            if (this.selectRows.length > 0) {
                let ids = []
                for (let row of this.selectRows) {
                    ids.push(row.id)
                }
                if (ids.length === 1) {
                    this.doDelete(ids)
                } else {
                    this.$Modal.confirm({
                        title: '操作提示',
                        content: '<p>确认删除'+ids.length+'条记录?</p>',
                        onOk: () => {
                            this.doDelete(ids)
                        }
                    })
                }
            } else {
                this.$bus.alert('warning', '请至少选择一条记录')
            }
        },
        doDelete (ids) {
            let url = this.detailURL + '/delete/' + this.formDetailItem.courseId
            this.$ajax.post(url, ids).then((response) => {
                let {code, msg} = response.data
                if (code === 0) {
                    this.$bus.alert('success', msg)
                    this.refresh()
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        save () {
            this.$refs['formItem'].validate((valid) => {
                if (valid) {
                    let url = this.baseURL + '/saveOrUpdate'
                    this.$ajax.post(url, this.formItem).then((response) => {
                        let {code, data, msg} = response.data
                        if (code === 0) {
                            this.$bus.alert('success', '操作成功')
                            this.formItem = data
                            this.formDetailItem.courseId = data.id
                            this.disabled = false
                        } else {
                            this.$bus.alert('error', msg)
                        }
                    })
                }
            })
        },
        close () {
            this.$store.state.app.close = true
            this.$bus.closePageToLink()
        },
        saveDetails () {
            this.$refs['formDetailItem'].validate((valid) => {
                if (valid) {
                    this.formDetailItem.itemType = 1
                    let url = this.detailURL + '/saveOrUpdate'
                    this.$ajax.post(url, this.formDetailItem).then((response) => {
                        let {code, data, msg} = response.data
                        if (code === 0) {
                            this.$bus.alert('success', '操作成功')
                            this.formDetailItem = data
                        } else {
                            this.$bus.alert('error', msg)
                        }
                    })
                }
            })
        },
        clickTabs (name) {
            this.selectTabPane = name
            if (name === '2') {
                this.refresh()
            }
        },
        changeProject (option) {
            this.formDetailItem.itemId = option.value
            this.formDetailItem.itemName = option.label
            let url =  this.projectURL + '/findById/' + option.value
            this.$ajax.get(url).then((response) => {
                let {code, data, msg} = response.data
                if (code === 0) {
                    this.selectProject = data
                    this.formDetailItem.price = data.price
                    if (this.formDetailItem.id === '') {
                        this.formDetailItem.quantity = 1
                    }
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        changeSelect (rows) {
            this.selectRows = rows
        },
        changeTotalSize (totalSize) {
            this.pageModel.totalSize = totalSize
        },
        changePageNumber (pageNumber) {
            this.pageModel.pageNumber = pageNumber
        },
        changePageSize (pageSize) {
            this.pageModel.pageSize = pageSize
        },
        refresh () {
          this.$refs.iviewTable.refresh()
        },
        reset () {
            this.resetForm()
            this.resetDetailForm()
        },
        resetForm () {
            this.$refs.formItem.resetFields()
        },
        resetDetailForm () {
            this.$refs.formDetailItem.resetFields()
        }
    },
    beforeRouteEnter (to, from, next) {
        next(vm => {
            vm.init()
        })
    },
    beforeRouteLeave (to, from , next) {
        this.$bus.routeLeave(next, this.selectTabPane)
    },
    watch: {
        'formDetailItem.courseId': function (val, oldValue) {
            this.queryModel.defaultFilters[0] = {'field': 'course_id', 'value1': val, 'operate': '=='}
        }
    }
}
</script>

<style>

</style>
